<template>
    <div class="app-container home">
        <div class="map-container" id="map-container"></div>


        <div class="list-container-flod-btns" @click="foldVisitData">
            <icon-menu-fold class="icon" v-if="!showVisitData"/>
            <icon-menu-unfold class="icon" v-if="showVisitData"/>
        </div>

        <div class="search-container">
            <el-input
                clearable
                v-model="searchText"
                class="w-50 m-2"
                placeholder="输入关键字搜索"
                :prefix-icon="Search"
                @change="search"
            />
            <div class="res-list-container" v-if="showSearchRes">

                <el-button v-if="searchedLoading" loading type="text"></el-button>
                <span class="no-data" v-if="!searchedLoading && searchedList.length == 0" >无数据</span>

                <template v-if="searchedList && searchedList.length > 0">
                    <div class="item" v-for="(item, index) in searchedList" :key="index" :class="item == selectedItem?'selected':''" @click="selectItem(item)">
                        <div class="address">{{item.address}}</div>
                        <div class="head-name">【{{item.headName}}】</div>
                    </div>
                </template>

            </div>
        </div>

        <Transition name="list">
            <div class="list-container" v-show="showVisitData">
                <div class="time-picker-container">
                    <span>查询时间段：</span>
                    <el-date-picker
                        v-model="startTime"
                        type="datetime"
                        size="small"
                        placeholder="Select date and time"
                    />
                    <span> - </span>
                    <el-date-picker
                        v-model="endTime"
                        type="datetime"
                        size="small"
                        placeholder="Select date and time"
                    />
                    <el-button style="margin-left: 10px" type="primary" size="small" @click="requestVisitList">查询</el-button>
                </div>

                <div class="data-list-container">
                    <el-table :data="visitDataList" stripe style="width: 100%" empty-text="没有数据" v-loading="visitDataLoading">
                        <el-table-column prop="createTime" label="时间" width="120">
                            <template #default="scope">
                                <span> {{ scope.row.createTime && new Date(scope.row.createTime).format('M月d日 hh:mm') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userName" label="网格员">
                            <template #default="scope">{{ scope.row.userName || '-' }}</template>
                        </el-table-column>
                        <el-table-column prop="address" label="位置">
                            <template #default="scope">{{ scope.row.address || '-' }}</template>
                        </el-table-column>
                        <el-table-column prop="weather" label="天气">
                            <template #default="scope">{{ scope.row.weather || '-' }}</template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注">
                            <template #default="scope">{{ scope.row.remark || '-' }}</template>
                        </el-table-column>
                        <el-table-column label="操作" width="70">
                            <template #default="scope">
                                <el-button type="text" size="small" @click="showVisitOnMap(scope.row)" v-if="!layerMap[scope.row.id]">查看</el-button>
                                <el-button type="text" size="small" @click="hideVisitOnMap(scope.row)" v-if="layerMap[scope.row.id]">隐藏</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="pagination-container">
                    <el-pagination background small layout="prev, pager, next" :total="dataTotalSize" v-model:current-page="currentPage" :page-size="pageSize"/>
                </div>
            </div>
        </Transition>
    </div>
</template>

<script setup name="Index">
import {computed, nextTick, onMounted, ref, watch} from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import VisitApi from '../api/visit';
import startIcon from '../assets/images/start.png';
import endIcon from '../assets/images/end.png';
import {  Search } from '@element-plus/icons-vue'
import {getBisFamilyInfoList,getBisFamily,addBisFamilyInfo,updateBisFamilyInfo,delBisFamilyInfo} from "@/api/grid/housekeeper";
import LocationIcon from "../assets/images/location.png";

const version = ref('3.8.3')

const map = ref(null);
const startTime = ref(new Date(new Date().getTime() - 10 * 24 * 3600000));
const endTime = ref(new Date());
const currentPage = ref(1);
const pageSize = ref(10);
const dataTotalSize = ref(0);
const visitDataList = ref([]);
const visitDataLoading = ref(false);
const showVisitData = ref(true);

const layerMap = ref({});

const searchText = ref('');
const selectedItem = ref({});
const searchedList = ref([]);
const searchedLoading = ref(false);
const houseMarker = ref({})
const showSearchRes = ref(false)


onMounted(() => {
    initMap();

    requestVisitList();


    search();
})

watch(currentPage, () => {
    requestVisitList();
})

//搜索
const search = ()=>{
    if (!searchText.value){
        searchedList.value = [];
        showSearchRes.value = false;
        return;
    }
    showSearchRes.value = true;
    searchedLoading.value = true;
    getBisFamilyInfoList({
        pageNum: 1,
        pageSize: 1000,
        headName: searchText.value
    }).then(response => {
       if (response.code == 200 && response.rows){
           searchedList.value = response.rows;
       }
    }).finally(()=>{
        searchedLoading.value = false;
    })
}

//选择房屋
const selectItem = (item)=>{
    selectedItem.value = item;

    showLocationOnMap(item);
}

//展示房屋位置
const showLocationOnMap = (selectedItem)=>{
    let lon = selectedItem.communityLongitude;
    let lat = selectedItem.communityLatitude;
    if (!lon || !lat) return;

    map.value.remove(houseMarker.value);

    houseMarker.value = new AMap.Marker({
        position: new AMap.LngLat(lon,  lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        anchor: 'bottom-center',
        icon: new AMap.Icon({
            image: LocationIcon,
            size: [36, 36],
            imageSize: [36, 36],
        }),
    });
    map.value.add(houseMarker.value);
    map.value.setFitView(houseMarker.value, true)
}

//展开/折叠走访数据列表
const foldVisitData = ()=>{showVisitData.value = !showVisitData.value}

//隐藏路线
const hideVisitOnMap = (item) => {
    let id = item.id;
    if (!layerMap.value[id]) {
        return;
    }
    map.value.remove(layerMap.value[id]);
    layerMap.value[id] = undefined;
}


//展示路线
const showVisitOnMap = (item) => {
    let id = item.id;
    if (!id) return;
    let data = item.data && JSON.parse(item.data);

    if (layerMap.value[id]) {
        map.value.add(layerMap.value[id]);
        map.value.setFitView(layerMap.value[id], true)
        return;
    }

    let path = [];
    for (let d of data) {
        path.push(new AMap.LngLat(d.longitude || d.lon, d.latitude || d.lat))
    }

    if (path.length == 0) {
        return;
    }

    let polyline = new AMap.Polyline({
        path: path,
        strokeWeight: 5, // 线条宽度，默认为 1
        strokeColor: '#6585be', // 线条颜色
        strokeOpacity: 1, //透明度
        lineJoin: 'round' // 折线拐点连接处样式
    });
    let startMarker = new AMap.Marker({
        position: path[0],   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        anchor: 'bottom-center',
        icon: new AMap.Icon({
            image: startIcon,
            size: [36, 36],
            imageSize: [36, 36],
        }),
    });
    let endMarker = new AMap.Marker({
        position: path[path.length - 1],   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        anchor: 'bottom-center',
        icon: new AMap.Icon({
            image: endIcon,
            size: [36, 36],
            imageSize: [36, 36],
        }),
    });

    layerMap.value[id] = [polyline, startMarker, endMarker];

    map.value.add(layerMap.value[id]);
    map.value.setFitView(layerMap.value[id], true)
}

//查询数据
const requestVisitList = () => {
    visitDataLoading.value = true;

    VisitApi.getVisitList({
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        startTime: startTime.value.format('yyyy-MM-dd hh:mm:ss'),
        endTime: endTime.value.format('yyyy-MM-dd hh:mm:ss')
    }).then((resp) => {
        if (resp && resp.code == 200 && resp.rows) {
            visitDataList.value = resp.rows;
            dataTotalSize.value = resp.total;
        }
    }).finally(() => {
        visitDataLoading.value = false;
    })
}

//初始化地图
const initMap = () => {
    AMapLoader.load({
        key: "9c4d1e3eb0c12d91bb25ccaae913615a",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [''],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        map.value = new AMap.Map("map-container", {  //设置地图容器id
            viewMode: "3D",    //是否为3D地图模式
            zoom: 15,           //初始化地图级别
            center: [121.310626, 31.915724], //初始化地图中心点位置
        });
    }).catch(e => {
        console.log(e);
    })
}


</script>

<style scoped lang="scss">

.list-enter-active,
.list-leave-active {
    transition: opacity 0.3s ease;
}

.list-enter-from,
.list-leave-to {
    opacity: 0;
}

.home {
    position: relative;

    .map-container {
        width: 100%;
        height: 100%;
    }

    .search-container{
        width: 260px;
        //background: #fff;
        //box-shadow: 0 0 5px #2d5cf622;
        position: absolute;
        left: 30px;
        top: 30px;
        //padding: 10px;

        >.res-list-container{
            width: 100%;
            background: #fff;
            margin-top: 10px;
            border-radius: 5px;
            box-shadow: 0 0 5px #2d5cf622;
            text-align: center;
            padding: 10px;

            >.no-data{
                color: #999;

            }

            >.item{
                display: flex;
                color: #444;
                padding: 10px 5px;
                cursor: pointer;
                transition: 0.15s;
                >.address{
                    font-weight: bold;
                }
                >.head-name{
                }
            }
            >.item:hover{
                background: #88b9f9;
                color: #fff;
            }
            >.item:active{
                background: #5a9cf8;
                color: #fff;
            }
            >.item.selected{
                background: #5a9cf8;
                color: #fff;
            }
        }
    }

    .list-container-flod-btns {
        position: absolute;
        right: 30px;
        top: 30px;
        z-index: 1000;
        background: #fff;
        padding: 3px;

        font-size: 1.3em;
        color: #5a9cf8;
        cursor: pointer;
    }

    .list-container-flod-btns:hover {
        color: #5a9cf8aa;
    }

    .list-container {
        position: absolute;
        right: 30px;
        top: 30px;
        max-width: 90%;
        max-height: 60%;
        background: #fff;
        box-shadow: 0 0 5px #2d5cf622;
        padding: 10px 10px 20px 10px;
        overflow: auto;

        .time-picker-container{
            margin-right: 30px;
        }

        .data-list-container {
            margin: 10px 0;
        }

        .pagination-container {
            width: 100%;
        }
    }

}
</style>

<style>
.el-date-editor{
    --el-date-editor-width: auto;
}
</style>

